var Emitter = require('emitter');
var ArrayMgr = require('arraymgr');

function Outlet() {
	Emitter.call(this);
}

Outlet.prototype = new Emitter();

Outlet.prototype.init = function() {
  this.modules = new ArrayMgr();
  return this;
};

// Send data to all connected modules
Outlet.prototype.broadcast = function(data) {
  this.modules.iterate(function(m, i) {
    var module = m.module;
    var event = m.event;
    var key = 'on_' + event;
    if (module[key]) {
      module[key](data);
    } else {
      console.log('module missing function on_%s', event);
    }
  });
};

// Dispatch data to a random module
Outlet.prototype.dispatch = function(data) {
  var index = Math.floor(Math.random() * this.modules.length());
  var m = this.modules.get(index);
  if (m) {
    var key = 'on_' + m.event;
    m.module[key](data);
  }
};

Outlet.prototype.connect = function(module, event) {
  this.modules.add({module: module, event: event});
};

Outlet.prototype.dispose = function() {
  this.modules.empty();
};

module.exports = Outlet;
